import Row from "./Row";
import ColGroup from "./ColGroup";
import { useForm } from "../../../framework/common/context/metadata-context";
import clsx from "clsx";
import { forwardRef } from "react";
import useTableReady from "./useTableReady";
import { fieldFilter, fieldFilterNormal } from "../../../framework/common/utils/filter";
import set from "lodash/set";
import get from "lodash/get";
import { InjectProvider } from "../../../framework/common/context/inject-context";
import { useSubscribe } from "../../../framework/common/eventBus";
import { useUpdate } from "ahooks";

export default forwardRef(function ({ scale, hasOperationColumn, paddingRight, data = [], group, isSetFixedColumnPc }, ref) {
  const form = useForm();
  const updater = useUpdate();
  const { isReady } = useTableReady(group.code + ".ready");

  useSubscribe("field.blur", () => {
    updater();
  });
  if (isReady === false) return null;

  let fields = group.fields.filter(fieldFilter) || [];
  let showTotalFields = fields.filter((f) => f.designProps?.isTotal === true) || [];
  //如果没有合计列，或者没有数据，或者是编辑表格就不显示summary
  if (showTotalFields.length === 0 || data.length === 0) {
    return null;
  }
  let totalData = {};
  //计算合计列的合计值
  showTotalFields.forEach((s) => {
    s.preFixStr = "合计：";
    let fieldCode = s.code;
    let total = 0;
    data.forEach((d) => {
      total += Number(d[fieldCode]) || 0;
    });
    totalData[fieldCode] = total;
  });

  let dataPrefix = "form.form_data.childrenSummary.";

  //把合计列计算好的信息放入form_data.childrenSummary暂存
  set(form.data, dataPrefix + group.code, [totalData]);

  let normalFilterFields = group.fields.filter(fieldFilterNormal);
  let theTable = (
    <div style={{ paddingRight }} className={clsx("runtime-data-list  overflow-hidden  summary", hasOperationColumn && "hasOperationColumn", form.showBorder && "hasBorder")}>
      <table ref={ref} className="min-w-full table-process-form" style={{ width: group?.style?.width + "px" }}>
        <ColGroup scale={scale} isFiexedTable={isSetFixedColumnPc} group={group} fields={group.fields} fixedColum={998}></ColGroup>
        <tbody>
          <InjectProvider value={{ prefixStr: "合计：" }}>
            {get(form.data, dataPrefix + group.code, []).map((row, index) => (
              <Row
                filterFields={fields}
                normalFilterFields={normalFilterFields}
                fixedColum={998}
                isSummary={true}
                dataPrefix={dataPrefix}
                isFiexedTable={isSetFixedColumnPc}
                groupCode={group.code}
                group={group}
                rowIndex={index}
                key={index}
                row={row}
                fields={group.fields}
              ></Row>
            ))}
          </InjectProvider>
        </tbody>
      </table>
    </div>
  );
  //如果没有固定列
  if (isSetFixedColumnPc === false) {
    return <div className="relative runtime-data-list-wrapper summary-wrapper">{theTable}</div>;
  }

  let fixedColumnPc = (group.fixedColumnPc || 0) + (group.loop_table_sid ? 1 : 0);
  return (
    <div className="relative runtime-data-list-wrapper summary-wrapper">
      {theTable}
      <table className="absolute top-0 left-0 bg-white runtime-data-list fixed-table table-process-form">
        <ColGroup scale={scale} fixedColum={fixedColumnPc} group={group} fields={group.fields}></ColGroup>
        <tbody>
          <InjectProvider value={{ prefixStr: "合计：" }}>
            {get(form.data, dataPrefix + group.code, []).map((row, index) => (
              <Row
                filterFields={fields}
                normalFilterFields={normalFilterFields}
                isSummary={true}
                dataPrefix={dataPrefix}
                isFiexedTable={true}
                fixedColum={fixedColumnPc}
                disableHeightCalculcate={true}
                group={group}
                groupCode={group.code}
                rowIndex={index}
                key={index}
                row={row}
                fields={group.fields}
              ></Row>
            ))}
          </InjectProvider>
        </tbody>
      </table>
    </div>
  );
});
